import axios from "axios";
import {getRefershToken,removeRefershToken} from '../../config/stroage'
import {refreshToken,addRequest} from '../refresh'
import { message } from "antd";
export const request = axios.create({ timeout: 20000 });
request.interceptors.request.use(
  (config) => {
    // 请求带着短token 短token没过期不验证长token  过期就验证长token
    if(getRefershToken()){
      config.headers['Authorization'] = `${getRefershToken()}`
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
request.interceptors.response.use(
  ({ data,config }) => {
    return new Promise((resolve,reject)=>{
      if(data.code === 409){
        // 清除失效的短token
        removeRefershToken()
        addRequest(()=>resolve(request(config)))
        refreshToken()
      }else if(data.code === 401){
        reject(data.msg)
        message.error('未登录 请去登录', 1, ()=>{ window.location.hash="/login"})
      }else{
        resolve(data)
      }
    })
  },
  (err) => {
    return Promise.reject(err)
  }
);
